package com.hmdp.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.FOLLOW_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@RequiredArgsConstructor
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    private final StringRedisTemplate stringRedisTemplate;

    private final IUserService userService;
    /**
     * 关注或取关
     * @param followUserId
     * @param isFollow
     * @return
     */
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        if (isFollow == null || followUserId == null || followUserId <= 0){
            return Result.fail("参数有误");
        }
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        if (user == null){
            return Result.fail("用户未登录");
        }
        String key = FOLLOW_KEY + user.getId();
        // 1.判断到底是关注还是取关
        if (isFollow){
            // 2.关注，新增数据
            Follow follow = new Follow();
            follow.setFollowUserId(followUserId);
            follow.setUserId(user.getId());
            follow.setCreateTime(LocalDateTime.now());
            boolean save = save(follow);
            if (save){
                // 把关注用户的id，放入redis的set集合 sadd userId followerUserId
                stringRedisTemplate.opsForSet().add(key, followUserId.toString());
            }
        } else {
            // 3.取关，删除 delete from tb_follow where user_id = ? and follow_user_id = ?
            boolean remove = remove(Wrappers.<Follow>lambdaQuery().eq(Follow::getUserId, user.getId()).eq(Follow::getFollowUserId, followUserId));
            if (remove){
                // 把关注用户的id从Redis集合中移除
                stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
            }
        }
        return Result.ok();
    }

    /**
     * 判断是否关注
     * @param followUserId@return
     */
    @Override
    public Result isFollow(Long followUserId) {
        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        if (user == null){
            return Result.fail("用户未登录");
        }
        // 2.查询是否关注 select count(*) from tb_follow where user_id = ? and follow_user_id = ?
        int count = count(Wrappers.<Follow>lambdaQuery().eq(Follow::getUserId, user.getId()).eq(Follow::getFollowUserId, followUserId));
        // 3.判断
        return Result.ok(count > 0);
    }

    /**
     * 共同关注
     *
     * @param id
     * @return
     */
    @Override
    public Result followCommons(Long id) {
        if (id == null || id <= 0){
            return Result.fail("参数有误");
        }
        // 1.获取当前用户
        UserDTO user = UserHolder.getUser();
        if (user == null){
            return Result.fail("用户未登录");
        }
        String key = FOLLOW_KEY + user.getId();
        String key2 = FOLLOW_KEY + id;
        // 2.求交集
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key, key2);
        if (intersect == null || intersect.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        // 3.解析id集合
        List<Long> longList = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        // 4.查询用户
        List<UserDTO> userDTOS = userService.listByIds(longList).stream().map(this::convertToDTO).collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

    private UserDTO convertToDTO(User user) {
        UserDTO userDTO = new UserDTO();
        userDTO.setId(user.getId());
        userDTO.setNickName(user.getNickName());
        userDTO.setIcon(user.getIcon());
        return userDTO;
    }
}
